package com.budwk.app.sqfwV2.service.wasteCategoryNew;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.FromSummaryComponent;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.SqfwFormSummaryFieldEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowBusinessParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.PdfGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.BasePdfGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.pdfService.CompleteFlowCommonPdfService;
import com.budwk.app.sqfwDoc.codeGeneratorV2.result.GeneratorPdfWordResult;
import com.budwk.app.sqfwV2.dto.dto.WasteCategoryNewPdfDTO;
import com.budwk.app.sqfwV2.enums.WasteCategoryFileServiceEnum;
import com.budwk.app.sqfwV2.generator.wasteCategory.pdf.RefuseClassifyDocGenerator;
import com.budwk.app.sqfwV2.generator.wasteCategory.pdf.RefuseClassifyYuHongDocGenerator;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.DateUtils;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 东方祥云低代码1.1
 * @since 2024-03-11
 *
 */
@IocBean
public class WasteCategoryNewPdfService extends CompleteFlowCommonPdfService{

    @Override
    public void createPdfAndMsg(CompleteFlowPdfParamForController paramForController) {
        super.createPdfAndMsg(paramForController);
    }

    @Override
    public GeneratorPdfWordResult createPdfSync(CompleteFlowPdfParamForController paramForController) {
        return super.createPdfSync(paramForController);
    }

    /**
     * 获取用户自定义字段 代码生成器已经自动填充
     * 无需特殊修改
     *
     * @param paramData json字符串
     * @return 结果
     */
    @Override
    protected AbstractCustomerPdfCreateField getCustomerPdfField(String paramData) {
        return JSONObject.parseObject(paramData, WasteCategoryNewPdfDTO.class);
    }

    /**
    * 允许用户自定义填充在创建pdf时所提供的数据
    *
    * @param pdfGenerateParam 创建pdf所提供的数据
    */
    @Override
    protected void customerPopularPdfGenerateParam(PdfGenerateParam pdfGenerateParam) {

    }

    /**
     * 在这里设置生成pdf的所有generator
     *
     * @param pdfGenerateParam 创建pdf的参数
     * @return 生成pdf的generator合集
     */
    @Override
    protected List<BasePdfGenerator> getPdfGenerator(PdfGenerateParam pdfGenerateParam) {
        List<BasePdfGenerator> generatorList = Lists.newArrayList();
        // 在这里添加自己的generator
        RefuseClassifyDocGenerator docGenerator = new RefuseClassifyDocGenerator();
        if (docGenerator.pdfCreateConditionCheck(pdfGenerateParam)) {
            generatorList.add(docGenerator);
        }
        RefuseClassifyYuHongDocGenerator yuHongDocGenerator = new RefuseClassifyYuHongDocGenerator();
        if (yuHongDocGenerator.pdfCreateConditionCheck(pdfGenerateParam)) {
            generatorList.add(docGenerator);
        }
        return generatorList;
    }

    /**
    * 用户自定义下载pdf文件的名称
    *
    * @param pdfGenerateParam 创建pdf所提供的参数
    * @return 结果
    */
    @Override
    protected String getDownloadFileName(PdfGenerateParam pdfGenerateParam) {
        return WasteCategoryFileServiceEnum.ONE_PDF.getFileName();
    }

    private void checkParam(Sqfw_formSummary_new formSummary) {
        if (formSummary == null) {
            throw new AppException("请求参数为空！");
        }
        if (StringUtils.isEmpty(formSummary.getParamData())) {
            throw new AppException("请求参数paramData为空！");
        }
    }

    private Sqfw_formSummary_new queryLastData(Sqfw_formSummary_new formSummary, WasteCategoryNewPdfDTO pdfDTO, String userId) {
        if (StringUtils.isEmpty(pdfDTO.getAddress())) {
            throw new AppException("调查地点不能为空!");
        }
        SqfwFormsummaryNewService formsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
        SysUserService userService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user user = userService.fetch(userId);
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup where = cnd.where();
        where.andEquals(Sqfw_formSummary_new::getUnitId, user.getUnitId())
                .andEquals(Sqfw_formSummary_new::getType, SupportBusinessTypeEnum.REFUSE_CLASSIFY.getName())
                .andEquals(Sqfw_formSummary_new::getDetailAddress, formSummary.getDetailAddress());
        List<Sqfw_formSummary_new> formSummaryNews = formsummaryNewService.query(cnd);
        if (formSummaryNews.size() == 0) {
            return null;
        }
        // 取出小于当前提交时间的所有数据
        List<Sqfw_formSummary_new> formSummaryData = formSummaryNews.stream().filter(e -> e.getFillDate().getTime() < formSummary.getFillDate().getTime()).collect(Collectors.toList());
        if (formSummaryData.size() > 0) {
            return formSummaryData.get(0);
        }
        return null;
    }

    @Override
    protected void beforeInsertForSummary(Sqfw_formSummary_new formSummary) {
        // 参数校验
        checkParam(formSummary);
        // 入库前参数准备
        buildBeforeParam(formSummary, SecurityUtil.getUserId());
    }

    private void buildBeforeParam(Sqfw_formSummary_new formSummary, String userId) {
        // 数据准备
        WasteCategoryNewPdfDTO pdfDTO = JSONObject.parseObject(formSummary.getParamData(), WasteCategoryNewPdfDTO.class);
        if (StringUtils.isEmpty(formSummary.getDetailAddress())) {
            SysUserService userService = NutzIocUtils.getBean(SysUserService.class);
            Sys_user user = userService.fetch(SecurityUtil.getUserId());
            String detailAddress = String.format("%s%s%s%s%s%s", StrUtil.formatStr(user.getProvince()),
                    StrUtil.formatStr(user.getCity()),
                    StrUtil.formatStr(user.getDistrict()),
                    StrUtil.formatStr(user.getCounty()),
                    StrUtil.formatStr(user.getCommunity()),
                    StrUtil.formatStr(pdfDTO.getAddress()));
            formSummary.setDetailAddress(detailAddress);
        }
        // 2 获取上一次的数据
        Sqfw_formSummary_new lastData = queryLastData(formSummary, pdfDTO, userId);
        if (lastData != null) {
            pdfDTO.setLastSummaryId(lastData.getId());
        }
        // 隐患状态
        pdfDTO.setIssueStatus(pdfDTO.getProblems().equals("无") ? "false" : "true");
        if (pdfDTO.getFillDate() != null) {
            formSummary.setFillDate(DateUtils.toDateByLocalDateTime(pdfDTO.getFillDate()));
        }
        // 设置检查状态、
        buildInpsectionStatus(formSummary, lastData, userId);
        WasteCategoryNewPdfDTO f = StrUtil.serializerData(WasteCategoryNewPdfDTO.class, pdfDTO);
        formSummary.setParamData(JSONObject.toJSONString(f));
    }

    private void buildInpsectionStatus(Sqfw_formSummary_new formSummary, Sqfw_formSummary_new lastData, String userId) {
        // 1 设置状态
        FromSummaryComponent.buildInspection(formSummary);
        // 2 修改上次数据
        if (lastData != null) {
            SysUserService userService = NutzIocUtils.getBean(SysUserService.class);
            Sys_user user = userService.fetch(userId);
            lastData.setCheckStatus(SqfwFormSummaryFieldEnum.check_status_checked.getCode())
                    .setUpdateDate(new Date())
                    .setUpdateBy(userId)
                    .setUpdateUserPhone(user.getMobile())
                    .setUpdateUserName(user.getUsername());
            SqfwFormsummaryNewService formsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
            formsummaryNewService.updateIgnoreNull(lastData);
        }
    }

    /**
    * 第五张表中的需要的类型，详情见 {@link SqfwFormSummaryConstants}
    *
    * @return 返回数据
    */
    @Override
    public String getSummaryType() {
        return SupportBusinessTypeEnum.REFUSE_CLASSIFY.getName();
    }

    @Override
    protected void customerPopularPdfGenerateParam(PdfGenerateParam pdfGenerateParam, Map<String, Object> customerBusinessDataMap) {
        // 获取新表数据
        Sqfw_formSummary_new formSummary = ((CompleteFlowBusinessParam) pdfGenerateParam.getBusinessParam()).getFormSummary();
        String paramData = formSummary.getParamData();
        // 数据前准备
        buildBeforeParam(formSummary, formSummary.getCreateBy());
        String paramData1 = formSummary.getParamData();
        if (!paramData1.equals(paramData)) {
            SqfwFormsummaryNewService sqfwFormsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
            Sqfw_formSummary_new formSummaryNew = sqfwFormsummaryNewService.fetch(formSummary.getId());
            formSummaryNew.setParamData(paramData1);
            sqfwFormsummaryNewService.updateIgnoreNull(formSummaryNew);

            WasteCategoryNewPdfDTO roadPdfDTO = JSONObject.parseObject(paramData1, WasteCategoryNewPdfDTO.class);
            pdfGenerateParam.setAbstractCustomerPdfCreateField(roadPdfDTO);
        }
    }
}
